package com.atguigu.tingshu.payment.strategy;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;

public interface PaymentStrategy {

    // 支付请求
    public abstract WeChatPayVo createJsapi(String paymentType, String orderNo);

    //获取支付类型
    public abstract String getPaymentType();

    default public WeChatPayVo requestWeChatPay(WxPayV3Config wxPayV3Config,
                                                String orderNo,
                                                String description,
                                                RSAAutoCertificateConfig rsaAutoCertificateConfig ,
                                                UserInfoFeignClient userInfoFeignClient){
        // 构建service
        JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
        //创建PrepayRequest对象封装所需要的数据
        PrepayRequest request = new PrepayRequest();
        request.setAppid(wxPayV3Config.getAppid());
        request.setMchid(wxPayV3Config.getMerchantId());
        request.setDescription(description);
        request.setOutTradeNo(orderNo);
        request.setNotifyUrl(wxPayV3Config.getNotifyUrl());
        // BigDecimal orderAmount = orderInfo.getOrderAmount();
        Amount amount = new Amount();
        amount.setTotal(1);
        request.setAmount(amount);
        Payer payer = new Payer();
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = userInfoFeignClient.getUserInfoById(userId).getData();
        payer.setOpenid(userInfo.getWxOpenId());
        request.setPayer(payer);

        // 调用微信支付接口
        PrepayWithRequestPaymentResponse prepayWithRequestPaymentResponse = service.prepayWithRequestPayment(request);
        //封装返回数据
        WeChatPayVo weChatPayVo = new WeChatPayVo();
        weChatPayVo.setTimeStamp(prepayWithRequestPaymentResponse.getTimeStamp());
        weChatPayVo.setNonceStr(prepayWithRequestPaymentResponse.getNonceStr());
        weChatPayVo.setPackageVal(prepayWithRequestPaymentResponse.getPackageVal());
        weChatPayVo.setSignType(prepayWithRequestPaymentResponse.getSignType());
        weChatPayVo.setPaySign(prepayWithRequestPaymentResponse.getPaySign());
        return weChatPayVo;
    }
}
